package com.iseastar.dianxiaosan.home.update;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;

import com.iseastar.guojiang.consts.AppConfig;
import com.iseastar.guojiang.consts.MsgID;

import droid.frame.App;
import droid.frame.Config;
import droid.frame.activity.ActivityMgr;
import droid.frame.ui.dialog.AppDialog;
import droid.frame.utils.android.Log;
import droid.frame.utils.http.HttpLoader;
import droid.frame.utils.http.HttpParam;
import droid.frame.utils.http.HttpReq;

/**
 * 店小三 版本升级相关业务逻辑（挪用裹儿）
 * 
 * @author coffee<br>
 *         2014年8月29日下午1:54:58
 */
public class UpgradeLogic {
	private static UpgradeLogic instance;

	private ProgressDialog mDialog;
	private String versionCode = null;

	private UpgradeLogic() {

	}

	public static UpgradeLogic getInstance() {
		if (instance == null) {
			instance = new UpgradeLogic();
		}
		return instance;
	}

	/**
	 * 店小三 发送版本检测的请求
	 */
	public void stationUpdateInfo(boolean isJam) {
		Map<String, Object> map = new HashMap<String, Object>();
		int type = isJam ? 0 : 1;
		map.put("isJam", type);
		map.put("version", getVersion());
		map.put("device", 1);
		map.put(HttpParam.postText, true);// get请求
		HttpReq req = new HttpReq(map, MsgID.station_update);
		req.setUrl(AppConfig.getTakeUrl() + "checkRelease");
		HttpLoader.getInstance().sendReq(req);
	}

	private String getVersion() {
		if (versionCode != null) {
			return versionCode;
		}
		Context context = App.getContext();
		PackageManager packageManager = context.getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		try {
			PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
			versionCode = packInfo.versionCode + "";
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	private int getVersionCode() {
		try {
			// 获取packagemanager的实例
			PackageManager packageManager = App.getContext().getPackageManager();
			// getPackageName()是你当前类的包名，0代表是获取版本信息
			PackageInfo packInfo = packageManager.getPackageInfo(App.getContext().getPackageName(), 0);
			int version = packInfo.versionCode;
			return version;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return 999999;
	}

	private String getPackageName() {
		try {
			// 获取packagemanager的实例
			PackageManager packageManager = App.getContext().getPackageManager();
			// getPackageName()是你当前类的包名，0代表是获取版本信息
			PackageInfo packInfo = packageManager.getPackageInfo(App.getContext().getPackageName(), 0);
			String packageName = packInfo.packageName;
			return packageName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return System.currentTimeMillis() + "";
	}

	public interface UpgradeCallback {
		public void execute();
	}

	/**
	 * 处理版本升级
	 * 
	 * @param activity
	 * @param upgradeBean
	 */
	public void processUpdate(final Activity activity, final UpgradeBean upgradeBean, final UpgradeCallback callback) {
		// 没有版本信息, 或者没有新版本
		if (upgradeBean == null) {
			return;
		}
		final AppDialog dialog = new AppDialog(activity);
		dialog.setTitle("检测到新版本,是否立即更新?");
		dialog.setContent(upgradeBean.getDescription());
		dialog.setCancelClickListener("取消", new OnClickListener() {

			@Override
			public void onClick(View v) {
				activity.finish();
			}
		});
		dialog.setConfirmClickListener("升级", new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
				showWaitDialog(activity);
				// 开始下载升级包
				new Thread(new Runnable() {
					public void run() {
						String filePath = downloadTheFile(upgradeBean.getDownloadUrl(), 2000);
						if (mDialog != null) {
							mDialog.cancel();
						}
						openFile(activity, filePath);
						// 只有非强制更新的版本，当下载完成选择不安装的时候才跳转到首页
						if ("2".equals(upgradeBean.getIsNeedUpdate()) == false) {
							if (callback != null) {
								callback.execute();
							}
						}
					}
				}).start();
			}
		});
		// 当前版本为强制更新版本
		if ("2".equals(upgradeBean.getIsNeedUpdate())) {
			dialog.setTitle("老版本已不可用,请升级");
			dialog.setCancelClickListener("退出", new OnClickListener() {
				@Override
				public void onClick(View v) {
					ActivityMgr.finishAll();
					activity.finish();
				}
			});
		} else {
			dialog.setTitle("发现新版本");
			dialog.setCancelClickListener("取消", new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (callback != null) {
						callback.execute();
					}

				}
			});
		}
		if (activity.isFinishing() == false) {
			activity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					dialog.show();
				}
			});
		}
		//
		// final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
		// builder.setMessage(upgradeBean.getDescription());
		// builder.setPositiveButton("升级", new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// dialog.cancel();
		// showWaitDialog(activity);
		// // 开始下载升级包
		// new Thread(new Runnable() {
		// public void run() {
		// String filePath = downloadTheFile(upgradeBean.getDownloadUrl(), 2000);
		// if (mDialog != null) {
		// mDialog.cancel();
		// }
		// openFile(activity, filePath);
		// // 只有非强制更新的版本，当下载完成选择不安装的时候才跳转到首页
		// if ("2".equals(upgradeBean.getIsNeedUpdate()) == false) {
		// if (callback != null) {
		// callback.execute();
		// }
		// }
		// }
		// }).start();
		// }
		// });
		// // 当前版本为强制更新版本
		// if ("2".equals(upgradeBean.getIsNeedUpdate())) {
		// builder.setTitle("老版本已不可用,请升级");
		// builder.setNegativeButton("退出", new OnClickListener() {
		// public void onClick(DialogInterface dialog, int which) {
		// ActivityMgr.finishAll();
		// activity.finish();
		// }
		// });
		// } else {
		// builder.setTitle("发现新版本");
		// builder.setNegativeButton("取消", new OnClickListener() {
		// public void onClick(DialogInterface dialog, int which) {
		// if (callback != null) {
		// callback.execute();
		// }
		// }
		// });
		// }
		// if (activity.isFinishing() == false) {
		// activity.runOnUiThread(new Runnable() {
		// @Override
		// public void run() {
		// AlertDialog dialog = builder.show();
		// dialog.setCanceledOnTouchOutside(false);
		// }
		// });
		// }
	}

	private void showWaitDialog(Activity activity) {
		mDialog = new ProgressDialog(activity);
		mDialog.setMessage("正在下载安装包,请稍后...");
		mDialog.setIndeterminate(false);
		mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mDialog.setCancelable(false);
		if (activity.isFinishing() == false) {
			mDialog.show();
		} else {
			mDialog = null;
		}
	}

	private void openFile(Activity activity, String filePath) {
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
		activity.startActivity(i);
	}

	/**
	 * 返回本地文件的存放路径
	 * 
	 * @param downloadUrl
	 * @return
	 */
	public String downloadTheFile(String downloadUrl, int reqId) {
		String filePath = null;
		try {
			URL url = new URL(downloadUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.connect();
			//
			InputStream is = conn.getInputStream();
			// 存储卡可用
			File file = null;
			String fileName = getPackageName() + "_update.apk";
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				file = new File(Config.getCacheDir(), fileName);
			} else {
				file = new File(App.getContext().getCacheDir(), fileName);
				try {
					// [文件夹705:drwx---r-x]
					String[] args1 = { "chmod", "705", App.getContext().getCacheDir().getCanonicalPath() };
					exec(args1);
					// [文件604:-rw----r--]
					String[] args2 = { "chmod", "604", file.getCanonicalPath() };
					exec(args2);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (file.exists() == false) {
				file.getParentFile().mkdirs();
				file.createNewFile();
			}
			filePath = file.getCanonicalPath();
			FileOutputStream fos = new FileOutputStream(file);
			int totalLen = conn.getContentLength();// byte
			Log.d("upgrade", totalLen);
			byte[] data = new byte[1024];
			int len = 0;
			int downLen = 0; // 已经下载的长度
			while ((len = is.read(data)) != -1) {
				fos.write(data, 0, len);
				downLen += len;
				// Message msg = Message.obtain();
				// msg.what = reqId;
				// msg.arg1 = downLen;
				// msg.arg2 = totalLen;
				// msg.obj = MathUtils.percent(downLen, totalLen);
				// HandlerMgr.sendMessage(msg, 0);
				if (mDialog != null) {
					mDialog.setMax(100);// 总大小.单位byte
					mDialog.setProgress(downLen * 100 / totalLen);// 已下载的
				}
			}
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return filePath;
	}

	public String exec(String[] args) {
		String result = "";
		ProcessBuilder processBuilder = new ProcessBuilder(args);
		Process process = null;
		InputStream errIs = null;
		InputStream inIs = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int read = -1;
			process = processBuilder.start();
			errIs = process.getErrorStream();
			while ((read = errIs.read()) != -1) {
				baos.write(read);
			}
			baos.write("/n".getBytes());
			inIs = process.getInputStream();
			while ((read = inIs.read()) != -1) {
				baos.write(read);
			}
			byte[] data = baos.toByteArray();
			result = new String(data);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (errIs != null) {
					errIs.close();
				}
				if (inIs != null) {
					inIs.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (process != null) {
				process.destroy();
			}
		}
		return result;
	}
}
